
package com.trial.area.address.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.trial.area.address.entity.DeliveryAddressVO;
import com.trial.area.address.param.DeliveryAddressParam;
import com.trial.area.address.service.DeliveryAddressService;
import com.trial.area.common.controller.BaseController;
import com.trial.area.common.param.SessionUserInfo;

/**
 * 收货地址Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class DeliveryAddressController extends BaseController {
    
    private Logger logger = LoggerFactory.getLogger(DeliveryAddressController.class);
    
    @Autowired
    private DeliveryAddressService deliveryAddressService;
    
    private final static String LIST_PAGE = "/deliveryAddress/list";
    
    private final static String VIEW_PAGE = "/deliveryAddress/view";
    
    private final static String UPDATE_PAGE = "/html5/delivery_address";

    @RequestMapping(value = "/check/address/toInsert")
    public ModelAndView intoInsert(String goodsId, String selectProperty) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        DeliveryAddressVO deliveryAddressVO = new DeliveryAddressVO();
        resultMap.put("deliveryAddressVO", deliveryAddressVO);
        if (StringUtils.isNotBlank(goodsId)) {
            resultMap.put("returnUrl", getPath() + "/check/goods/buy?goodsId=" + goodsId + "&selectProperty=" + selectProperty);
        }
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }

    @RequestMapping(value = "/check/address/toUpdate/{id}")
    public ModelAndView intoUpdate(@PathVariable String id, String goodsId, String selectProperty) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        DeliveryAddressVO deliveryAddressVO = deliveryAddressService.findById(id);
        resultMap.put("deliveryAddressVO", deliveryAddressVO);
        
        if (StringUtils.isNotBlank(goodsId)) {
            resultMap.put("returnUrl", getPath() + "/check/goods/buy?goodsId=" + goodsId + "&selectProperty=" + selectProperty);
        } else {
            resultMap.put("returnUrl", getPath() + "/check/account");
        }
        
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }

    @RequestMapping(value = "/check/address/update", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String update(DeliveryAddressVO deliveryAddressVO) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();

        String validMsg = deliveryAddressVO.valid();
        if (StringUtils.isNotBlank(validMsg)) {
            resultMap.put("result", false);
            resultMap.put("message", validMsg);
            return JSONObject.toJSONString(resultMap);
        }
        
        try {
            Integer affectCount = 0;
            if (deliveryAddressVO != null && StringUtils.isNotBlank(deliveryAddressVO.getDeliveryAddressId())) {
                affectCount = deliveryAddressService.update(deliveryAddressVO);
            } else if (deliveryAddressVO != null) {
                deliveryAddressVO.setDeliveryAddressId(UUID.randomUUID().toString());
                deliveryAddressVO.setDataStatus(0);
                deliveryAddressVO.setCreateUser(seUser.getUserId());
                deliveryAddressVO.setUserId(seUser.getUserId());
                affectCount = deliveryAddressService.insert(deliveryAddressVO);
            }
            if (affectCount != null && affectCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "新增或修改收货地址成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "新增或修改收货地址失败");
            }
        } catch (Exception e) {
            logger.error("新增或修改收货地址出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改收货地址出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/check/address/delete/{id}", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String delete(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer deleteCount = deliveryAddressService.delete(id);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除收货地址成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除收货地址失败");
            }
        } catch (Exception e) {
            logger.error("删除收货地址出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除收货地址出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/uncheck/address/list")
    public ModelAndView queryList(DeliveryAddressParam deliveryAddressParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<DeliveryAddressVO> dataList = deliveryAddressService.queryByPage(deliveryAddressParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", deliveryAddressParam);
        return new ModelAndView(LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/uncheck/address/view/{id}")
    public ModelAndView viewConfigInfo(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        DeliveryAddressVO deliveryAddressVO = deliveryAddressService.findById(id);
        resultMap.put("deliveryAddressVO", deliveryAddressVO);
        return new ModelAndView(VIEW_PAGE, resultMap);
    }
}
